import re

_SPLIT_CHARS = ('.', ' ', '+')

publisher_re = re.compile(r'.+-([^.]+)')  # exclude file extension

tv_season_ep_re = re.compile(r'[Ss](\d\d)[Ee](\d\d)')
resolution_re = re.compile(r'\(?(\d+[Xx]\d+)\)?')

video_codecs = ('[HX]\.?26[45]', 'MPEG(-?\d)?',
                'XVID', 'DIVX', 'AVC', 'AVCHD', 'VC-?1')
video_codec_re = re.compile('|'.join(video_codecs), re.IGNORECASE)

video_formats = ('CAM', 'TS', 'TC', 'DVD-?Rip', 'HDT?V?[-.]?Rip', 'PDTV',
                 'MiniBD', 'HDTV', 'DVD', 'HDVD', 'DVD5', 'DVD9', 'BR[-.]?Rip',
                 'BD-Remux', 'DVD-remux', 'HDVD-remux', 'R5', 'BD',
                 'WEB[-.]?DL', 'WEB[-.]?Rip', 'BD[-.]?Rip', 'Blu-?ray',
                 'DVDSCR')
video_format_re = re.compile('|'.join(video_formats), re.IGNORECASE)

bit_rates = ('480[ip]', '540[ip]', '720[ip]', '1080[ip]')
bit_rates_re = re.compile('|'.join(bit_rates), re.IGNORECASE)


def first_match(r, l):
    m = r.findall(l)
    if len(m) > 0:
        return m[0]
    else:
        return None


def tokenize(name):
    publisher = first_match(publisher_re, name)

    season_ep = first_match(tv_season_ep_re, name)
    season = None
    ep = None
    if season_ep:
        season, ep = map(int, season_ep)

    resolution = first_match(resolution_re, name)

    video_format = first_match(video_format_re, name)

    video_codec = first_match(video_codec_re, name)

    bit_rate = first_match(bit_rates_re, name)

    return {
        'video_format': video_format,
        'video_codec': video_codec,
        'bit_rate': bit_rate,
        'resolution': resolution,
        'publisher': publisher,
        'season': season,
        'ep': ep
    }


if __name__ == '__main__':

    import MySQLdb

    c = MySQLdb.connect(host='127.0.0.1', db='torrents', user='root')

    cur = c.cursor()

    cur.execute('select title from torrents')

    for r in cur.fetchall():
        if r[0].count('.') < 3 or re.match(u"[\u4e00-\u9fa5]+", r[0].decode('utf-8')):
            continue
        t = tokenize(r[0])
        if t['season'] and t['ep']:
            print t
